package ar.com.globallogic.promomr.api.controllers;

import java.security.Principal;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import ar.com.globallogic.promomr.domain.User;
import ar.com.globallogic.promomr.services.SecurityService;
import ar.com.globallogic.promomr.services.UserService;

@Controller
@RequestMapping("/api/users")
public class UserController {
	
	private UserService userService;
	private SecurityService securityService;
	
	@Autowired
	public UserController(UserService userService, SecurityService securityService) {
		super();
		this.userService = userService;
		this.securityService = securityService;
	}

	@RequestMapping(method = RequestMethod.POST)
	@ResponseStatus(value = HttpStatus.CREATED)
	public @ResponseBody User addUser(@RequestBody User user) {
		return userService.save(user);
	}
	
	@RequestMapping(value="{id}",method = RequestMethod.GET)
	@ResponseStatus(value = HttpStatus.OK)
	public @ResponseBody User getUser(@PathVariable String id) {
		return userService.findOne(id);
	}
	
	@RequestMapping(method = RequestMethod.GET)
	@ResponseStatus(value = HttpStatus.OK)
	public @ResponseBody User getUserByName(@RequestParam(value="userName", required=false) String userName) {
		return userService.findByUserName(userName);
	}
	
	@RequestMapping(value="authenticated",method = RequestMethod.GET)
	@ResponseStatus(value = HttpStatus.OK)
	public @ResponseBody User getAuthenticatedUser(Principal principal) {
		return securityService.getAuthenticatedUser();
	}
	
}
